import uuid

import api.repository.user_repository as user_repository
from api.vo.form.user_form import UserVo
from api.vo.ResponseVo import ResponsePageVo, ResponseVo
from api.vo.query.user_query import User_Query
from api.model.user_model import User
import base64

def exists(username: str):
        return ResponseVo(data=user_repository.exist_by_username(username))

def login(username: str, pwd: str):
        user = user_repository.get_by_username(username=username)
        if not user:
                return ResponseVo(code=400, msg="用户不存在")
        pwd = str(base64.b64encode(pwd.encode('utf-8')), "utf-8")
        if user.pwd != pwd:
                return ResponseVo(code=401, msg="密码错误")
        return ResponseVo()


def list(userQo: User_Query):
        data, count = user_repository.list(userQo=userQo)
        return ResponsePageVo(page=userQo.page, rows=userQo.rows, total=count, data=data)

def create(userVo: UserVo):
        pwd = str(base64.b64encode(userVo.pwd.encode('utf-8')), "utf-8")
        user = User(id=str(uuid.uuid4()),pwd=pwd,username=userVo.username,nickname=userVo.username,email=userVo.username)
        user_repository.add(user=user)
        return ResponseVo()